<?php

namespace Frieza\Modules\PhoneBlackWhite\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmUserType;
use Doraemon\model\Phone;
use Doraemon\model\PhoneBlackWhite as mPhoneBlackWhite;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\PhoneBlackWhite;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class PhoneBlackWhiteController extends Controller
{
    public const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $search = [];
        $params = $request->input();
        if ($params['phone']) {
            $search['phone'] = $params['phone'];
        }
        $list = PhoneBlackWhite::getList($page, $pageSize, $search);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('phone', 'phone')->placeholder("请输入手机号");
//                        $filter->equal('data_type', '标签')->checkbox(mPhoneBlackWhite::DATA_TYPE);
                    });

                    $filter->expand();
                });

                $grid->column('id');
                $grid->column('phone', '手机号');
                $grid->column("label", "标签")->display(function () {
                    $sLable = '';
                    if (!empty($this->uid)) {
                        $aMark = AdmUserType::getByUid($this->uid);

                        if (!empty($aMark['identity_mark'])) {
                            if (strpos($aMark['identity_mark'], '手机号存在风险') !== false) {
                                $sLable .= '手机号存在风险 | ';
                            }
                            if (strpos($aMark['identity_mark'], '批量注册刷交互') !== false) {
                                $sLable .= '批量注册刷交互';
                            }
                        }
                    }
                    return $sLable;

                });

//                $grid->column('data_type', '类型')->display(function () {
//                    return mPhoneBlackWhite::DATA_TYPE[$this->data_type];
//                });
                $grid->column('add_time', '添加时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->add_time);
                });

                $grid->column('edit_time', '修改时间')->display(function () {
                    if ($this->edit_time) {
                        return date("Y-m-d H:i:s", $this->edit_time);
                    } else {
                        return '--';
                    }

                });

                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
            });

        return $content
            ->header('虚拟手机号黑名单')
            ->description(' ')
            ->breadcrumb(['text' => '虚拟手机号黑名单列表'])
            ->row($gridList);
    }

    public function del($id)
    {
        $data = mPhoneBlackWhite::getById($id);
        if ($data) {
            $data['data_status'] = mPhoneBlackWhite::STATUS_DELETE;
            $data['edit_time'] = time();

            $rs = mPhoneBlackWhite::updateById($id, $data);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function add(Request $request, Content $content)
    {

        $request = $request->all();
        return $content
            ->header('虚拟手机号黑名单')
            ->breadcrumb(
                ['text' => '添加虚拟手机号黑名单']
            )
            ->body(self::editAction($request, $id = 0));

    }

    public function edit(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('虚拟手机号黑名单')
            ->breadcrumb(
                ['text' => '修改虚拟手机号黑名单']
            )
            ->body(self::editAction($request, $id));


    }


    public function editAction($request, $id = 0)
    {
        $data = [];
        if ($id != 0) {
            //修改
            $data = mPhoneBlackWhite::getById($id);
            $form = new Form($data);
            $form->hidden('id');
            $form->hidden('uid');

            $aMark = AdmUserType::getByUid($data['uid']);
            $budget_tag_checked = [];
            if (!empty($aMark['identity_mark'])) {
                if (strpos($aMark['identity_mark'], mPhoneBlackWhite::IDENTIFY_TYPE['1']) !== false) {
                    $budget_tag_checked[] = 1;
                }
                if (strpos($aMark['identity_mark'], mPhoneBlackWhite::IDENTIFY_TYPE['2']) !== false) {
                    $budget_tag_checked[] = 2;
                }
            }
            $form->text('phone', '手机号')->setWidth(4, 2)->required('不能为空')->help('请输入手机号');
            $form->checkbox('identify_type', '标签')->setWidth(4,
                2)->options(mPhoneBlackWhite::IDENTIFY_TYPE)->checked($budget_tag_checked);

        } else {
            //添加
            $form = new Form($data);
            $form->text('phone', '手机号')->setWidth(4, 2)->required('不能为空')->help('请输入手机号');
            $form->checkbox('identify_type', '标签')->setWidth(4, 2)->options(mPhoneBlackWhite::IDENTIFY_TYPE);
        }

        $form->action('/admin/PhoneBlackWhite/index/save');

        return $form->render();
    }

    public function editSubmit(Request $request, Content $content)
    {
        $request = $request->all();
        $rs = false;

        $sPhone = $request['phone'];
        $iUid = $request['uid'];
        $data['data_type'] = mPhoneBlackWhite::BLACK;
        $data['phone'] = substr_replace($sPhone, '****', 3, 4);
        $data['admin_id'] = Admin::user()->id;


        if (isset($request['id']) && $request['id']) {
            $data['edit_time'] = time();
            //修改
            $rs = mPhoneBlackWhite::updateById($request['id'], $data);

        } else {
            //添加
            $sEncryptPhone = PhoneCrypto::encrypt($sPhone, PhoneCrypto::CLIENT_YAPI, PhoneCrypto::VERSIN);
            $iUid = Phone::getUidByPhone($sEncryptPhone);
            if (!$iUid) {
                $error = new MessageBag([
                    'title' => '没有该用户'
                ]);
                return redirect('/admin/PhoneBlackWhite/index')->with(compact('error'));
            }
            $data['uid'] = $iUid;
            $data['phone'] = substr_replace($sPhone, '****', 3, 4);
            $data['add_time'] = time();

            $rs = mPhoneBlackWhite::add($data);
        }
        //添加标签
        $aIdentify = $request['identify_type'];

        //先删除 在保存
        $aMark = AdmUserType::getByUid($iUid);
        if (!empty($aMark['identity_mark'])) {
            if (strpos($aMark['identity_mark'], mPhoneBlackWhite::IDENTIFY_TYPE['1']) !== false) {
                AdmUserType::delIdentityMark([$iUid], mPhoneBlackWhite::IDENTIFY_TYPE['1']);
            }
            if (strpos($aMark['identity_mark'], mPhoneBlackWhite::IDENTIFY_TYPE['2']) !== false) {
                AdmUserType::delIdentityMark([$iUid], mPhoneBlackWhite::IDENTIFY_TYPE[2]);
            }
        }

        if (!empty($aIdentify)) {
            foreach ($aIdentify as $iIdentify) {
                if (!empty($iIdentify)) {
                    $sIdentifyName = mPhoneBlackWhite::IDENTIFY_TYPE[$iIdentify];
                    Log::info('33333', [$iIdentify, $sIdentifyName]);
                    AdmUserType::addIdentityMark([$iUid], $sIdentifyName);
                }
            }
        }

        if ($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/PhoneBlackWhite/index')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/PhoneBlackWhite/index')->with(compact('error'));
        }

    }
}